<template>
  <div style="min-height: 200px">
    <table class="table table-bordered table-vertical-middle" v-loading="guardLoading">
      <tr>
        <td :rowspan="2 + guards.length" class="text-center font-weight-bold" width="4%">
          反担保合同
        </td>
        <td class="td-label" width="12%">反担保人</td>
        <td class="td-label" width="12%">证件号</td>
        <td class="td-label" width="12%">联系电话</td>
        <td class="td-label" width="12%">住址</td>
        <td class="td-label" width="12%">反担保方式</td>
        <td class="td-label" width="12%">措施描述</td>
        <td class="td-label" colspan="2" width="24%">备注</td>
      </tr>
      <tr v-if="!viewMode">
        <td class="input-td">
          <input
            type="text"
            class="form-control text-center"
            placeholder="请填写"
            v-model="guardForm.gua_entity"
          />
        </td>
        <td class="input-td">
          <input
            type="text"
            class="form-control text-center"
            placeholder="请填写"
            @change="validatorNo(guardForm.gua_entity_cert_no)"
            v-model="guardForm.gua_entity_cert_no"
          />
        </td>
        <td class="input-td">
          <input
            type="text"
            class="form-control text-center"
            placeholder="请填写"
            v-model="guardForm.gua_entity_mobile"
          />
        </td>
        <td class="input-td">
          <input
            type="text"
            class="form-control text-center"
            placeholder="请填写"
            v-model="guardForm.gua_entity_address"
          />
        </td>
        <td class="input-td">
          <div @click="handlerMethodChange()" class="cursor-pointer">
            <div v-if="guardForm.gua_method" class="text-center">
              <div>{{ enumGuaMethod[guardForm.gua_method] || '-' }}</div>
              <small v-show="+guardForm.gua_method === 2" class="text-muted">
                股权:{{ guardForm.gua_stock_right || '-' }}%
              </small>
            </div>
            <div v-else class="text-muted text-center">
              <span>请选择</span>
              &nbsp;
              <i class="el-icon-arrow-down"></i>
            </div>
          </div>
        </td>
        <td class="input-td">
          <input
            type="text"
            class="form-control text-center"
            placeholder="请填写"
            v-model="guardForm.gua_des"
          />
        </td>
        <td class="input-td" colspan="2">
          <div class="d-flex align-items-stretch">
            <input
              type="text"
              class="form-control text-center"
              placeholder="请填写"
              v-model="guardForm.remark"
            />
            <el-button
              class="input-td-btn"
              type="primary"
              :loading="submitLoading"
              @click="submitGuard"
            >
              保存
            </el-button>
          </div>
        </td>
      </tr>
      <tr v-for="item in guards" :key="item.gua_contract_id">
        <td class="text-center">{{ item.gua_entity }}</td>
        <td class="text-center">{{ item.gua_entity_cert_no }}</td>
        <td class="text-center">{{ item.gua_entity_mobile }}</td>
        <td class="text-center">{{ item.gua_entity_address }}</td>
        <td class="text-center">
          <div>{{ enumGuaMethod[item.gua_method] || '-' }}</div>
          <div v-show="+item.gua_method === 2" class="text-muted">
            股权：{{ item.gua_stock_right || '-' }}%
          </div>
        </td>
        <td class="text-center">{{ item.gua_des }}</td>
        <td colspan="2" class="py-0 pr-0">
          <div class="d-flex align-items-center">
            <div class="flex-1">{{ item.remark }}</div>
            <template v-if="!viewMode">
              <el-button
                class="input-td-btn"
                icon="el-icon-edit"
                @click="handlerEdit(item)"
              ></el-button>
              <el-button
                class="input-td-btn"
                icon="el-icon-delete"
                @click="handlerDeleteConfirm(item)"
              ></el-button>
            </template>
          </div>
        </td>
      </tr>
    </table>

    <div class="text-center py-4">
      <el-button class="btn-long" @click="beforeClose">关闭</el-button>
    </div>

    <el-dialog
      width="450px"
      title="选择反担保方式"
      :append-to-body="true"
      :close-on-click-modal="false"
      class="text-center"
      :visible.sync="methodDialogVisible"
    >
      <div class="mb-3">
        <c-radio-group :options="methodRadios" v-model="guardMethod.type"></c-radio-group>
      </div>

      <div style="margin-left: 120px; width: 200px">
        <el-input
          v-model="guardMethod.equity"
          v-input-number="{ min: 0, max: 100, fixed: 2 }"
          placeholder="请填写股权比例"
          v-if="+guardMethod.type === 2"
        >
          <template slot="append">%</template>
        </el-input>
      </div>

      <div class="text-center py-4">
        <el-button type="primary" class="btn-long" @click="methodClose">确认</el-button>
        <!-- <el-button class="btn-long"
                   @click="methodDialogVisible=false">取消</el-button> -->
      </div>
    </el-dialog>

    <c-form-dialog
      ref="form"
      :visible.sync="formVisible"
      :form-items="formItems"
      :form-data="formData"
      :table-name="tableName"
      :table-id="tableId"
      @success="getData"
    ></c-form-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumGuaMethod, enumGuaMethodIndex } from '@/credit/plugins/enumTown'
import { phoneValidator, checkPhoneNumber } from '@/common/plugins/validator'
import { idCardValidate, licenseValidate } from '@vimi/utils-tool'
export default {
  components: {},
  props: {
    visible: Boolean,
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
    isRenewal: Boolean,
  },
  data() {
    const certNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!licenseValidate(value) && !idCardValidate(value)) {
        callback(new Error('错误的证件号，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      enumGuaMethodIndex,
      tableName: 'gua_contract',
      formVisible: false,
      formData: {},
      tableId: '',
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '反担保人',
            rules: [{ required: true, message: '请输入反担保人', trigger: 'blur' }],
          },
          attrs: { key: 'gua_entity', value: '', placeholder: '请输入反担保人' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '证件号',
            rules: [
              { required: true, message: '请输入证件号', trigger: 'blur' },
              { validator: certNoValidator, trigger: 'blur' },
            ],
          },
          attrs: { key: 'gua_entity_cert_no', value: '', placeholder: '请输入证件号' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入证件号', trigger: 'blur' },
              { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'gua_entity_mobile', value: '', placeholder: '请输入联系电话' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '住址',
            rules: [{ required: true, message: '请输入住址', trigger: 'blur' }],
          },
          attrs: { key: 'gua_entity_address', value: '', placeholder: '请输入住址' },
        },
        {
          tag: 'radio-group',
          itemAttrs: {
            label: '反担保方式',
            rules: [{ required: true, message: '请选择反担保方式', trigger: 'change' }],
          },
          attrs: {
            key: 'gua_method',
            value: '1',
            options: enumGuaMethod,
          },
        },
        {
          tag: 'number',
          itemAttrs: {
            label: '股权比例',
            rules: [{ required: true, message: '请输入股权比例', trigger: 'blur' }],
          },
          attrs: { key: 'gua_stock_right', value: '' },
          tagSlots: [{ name: 'append', slot: '%' }],
          ifRender(model) {
            return +model.gua_method === 2
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '措施描述',
            rules: [{ required: true, message: '请输入措施描述', trigger: 'blur' }],
          },
          attrs: { key: 'gua_des', value: '', placeholder: '请输入措施描述' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '备注',
          },
          attrs: { key: 'remark', value: '', placeholder: '备注' },
        },
        {
          tag: 'input',
          attrs: { key: 'gua_method_str', value: '' },
          ifShow: false,
          getValue: (v, model) => enumGuaMethodIndex[model.gua_method],
        },
        {
          tag: 'input',
          attrs: { key: 'gua_entity_type', value: '' },
          ifShow: false,
          getValue: (v, model) => (idCardValidate(model.gua_entity_cert_no) ? 2 : 1),
        },
        {
          tag: 'input',
          attrs: { key: 'customer_related_id', value: '' },
          ifShow: false,
        },
      ],
      enumGuaMethod: enumGuaMethod,
      guardLoading: false,
      submitLoading: false,

      contract: {},
      guards: [],

      guardForm: {},
      guardMethod: {
        type: '',
      },

      methodDialogVisible: false,
    }
  },
  computed: {
    ...mapGetters(['user', 'guardDatas']),
    relatedId() {
      return this.relatedData && this.relatedData.customer_related_id
    },
    methodRadios() {
      return Object.keys(this.enumGuaMethod).map(key => ({
        value: key,
        label: this.enumGuaMethod[key],
      }))
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    validatorNo(value) {
      if (idCardValidate(value)) {
        this.guardForm.gua_entity_type = 2
      } else if (licenseValidate(value)) {
        this.guardForm.gua_entity_type = 1
      } else {
        this.$message.warning('证件号格式错误')
        return false
      }
      return true
    },
    handlerEdit(row) {
      this.formVisible = true
      this.formData = row ? { ...row } : {}
      this.tableId = row ? row.gua_contract_id : ''
    },
    beforeClose() {
      this.$emit('dismiss', true)
    },

    async getData() {
      this.initGuardForm()
      this.guards = []
      await this.getGuard()
    },

    initGuardForm() {
      this.guardForm = {}
      this.guardMethod = {
        type: '',
      }
    },

    async getGuard() {
      if (!this.relatedId) return

      this.guardLoading = true
      await this.$utils.promise(this.$store.dispatch('getGuardsData', this.relatedId))
      this.guardLoading = false

      this.guards = this.guardDatas
    },

    async handlerDeleteConfirm(row) {
      this.$utils.msgbox({
        message: `确定删除反担保人${row.gua_entity}?`,
        beforeClose: () =>
          this.$api
            .deleteData(this.$serviceName, 'gua_contract', row.gua_contract_id)
            .then(() => {
              this.$message.success('删除成功！')
              this.getGuard()
            })
            .catch(() => this.$message.error(`删除失败，请重试！`)),
      })
    },

    submitGuard() {
      if (!this.validateGuard()) return
      if (!this.validatorNo(this.guardForm.gua_entity_cert_no)) return
      const data = {
        ...this.guardForm,
        customer_related_id: this.relatedId,
      }

      const num = this.guards.reduce((x, y) => (x > +y.order_num ? x : +y.order_num), 0)
      data.order_num = num + 1

      this.postGuardData(data)
    },

    validateGuard() {
      const enumValid = {
        gua_entity: '请填写反担保人',
        gua_entity_cert_no: '请填写证件号',
        gua_entity_address: '请填写住址',
        gua_entity_mobile: '请填写联系电话',
        gua_des: '请填写措施描述',
        gua_method: '请选择反担保方式',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.guardForm[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }
      if (!checkPhoneNumber(this.guardForm.gua_entity_mobile)) {
        this.$message.error('联系电话格式错误')
        return false
      }

      return true
    },

    handlerMethodChange() {
      if (this.guardForm.gua_method) {
        this.guardMethod = {
          type: this.guardForm.gua_method || '',
          equity: this.guardForm.gua_stock_right,
        }
      } else {
        this.guardMethod = {
          type: '1',
          equity: '',
        }
      }
      this.methodDialogVisible = true
    },

    methodClose() {
      if (+this.guardMethod.type === 2) {
        if (!this.guardMethod.equity) {
          return this.$message.error('请填写质押股权比例')
        }
        this.guardForm.gua_stock_right = this.guardMethod.equity
      } else {
        this.guardForm.gua_stock_right = ''
      }
      this.guardForm.gua_method = this.guardMethod.type
      this.methodDialogVisible = false
      this.guardMethod = {}
    },

    // handleEquityChange() {
    //   const { equity } = this.guardMethod
    //   if (equity && (+equity >= 100)) {
    //     this.guardMethod.equity = equity.replace(/^\w/, '')
    //   }
    // },

    async postGuardData(data) {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'gua_contract', {
          ...data,
          gua_method_str: enumGuaMethodIndex[data.gua_method],
          // 是否是续贷
          is_extended_loan: this.isRenewal ? 1 : 0,
        })
      )
      this.submitLoading = false
      if (res) {
        this.$emit('success', this.guards.length)
        this.$message.success('保存反担保人成功')
        this.initGuardForm()
        this.getGuard()
      } else {
        this.$message.error('保存反担保人失败')
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.input-td-btn {
  border-radius: 0;
  border: none;
  margin-right: 1px;
}
</style>
